import { query } from '../config/db.js';
import logger from '../config/logger.js';
import cache from '../config/redis.js';

/**
 * 获取所有新生分班信息(带分页)
 */
const getNewStudentClasses = async (req, res) => {
  console.log('获取新生分班列表');
  try {
    // 获取分页参数，默认第一页，每页10条
    const page = parseInt(req.query.page) || 1;  // 页码
    const pageSize = parseInt(req.query.pageSize) || 10;  // 每页条数
    const offset = (page - 1) * pageSize;  // 偏移量

    console.log('page', page);
    console.log('pageSize', pageSize);
    console.log('offset', offset);

    // 构建缓存键，包含分页参数
    const cacheKey = `newStudentClasses:page:${page}:pageSize:${pageSize}`;

    // 尝试从缓存获取数据
    const cachedData = await cache.get(cacheKey);
    if (cachedData) {
      return res.json({
        newStudentClasses: cachedData.data,
        pagination: cachedData.pagination,
        source: 'cache'
      });
    }

    // 缓存未命中，从数据库获取数据和总记录数
    const [dataResult, countResult] = await Promise.all([
      query(`SELECT * FROM new_student_classes ORDER BY id DESC LIMIT ${pageSize} OFFSET ${offset}`, []),
      query('SELECT COUNT(*) as total FROM new_student_classes', [])
    ]);

    const total = countResult.rows[0].total;
    const totalPages = Math.ceil(total / pageSize);

    // 构建返回数据和分页信息
    const responseData = {
      data: dataResult.rows,
      pagination: {
        page,
        pageSize,
        total,
        totalPages
      }
    };

    // 将数据存入缓存，过期时间设为1小时
    await cache.set(cacheKey, responseData, 3600);

    res.json({
      newStudentClasses: dataResult.rows,
      pagination: {
        page,
        pageSize,
        total,
        totalPages
      },
      source: 'database'
    });
  } catch (error) {
    if (error.name === 'DatabaseError') {
      logger.error('数据库查询错误:', { error: error.message, sql: error.sql, params: [Number(pageSize), Number(offset)] });
    } else {
      logger.error('获取新生分班列表错误:', error);
    }
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};


/**
 * 根据ID获取新生分班信息
 */
const getNewStudentClassById = async (req, res) => {
  console.log('根据ID获取新生分班信息');

  try {
    const { id } = req.params;
    const cacheKey = `newStudentClass:${id}`;

    // 尝试从缓存获取数据
    const cachedData = await cache.get(cacheKey);
    if (cachedData) {
      return res.json({
        newStudentClass: cachedData,
        source: 'cache'
      });
    }

    // 缓存未命中，从数据库获取
    const result = await query('SELECT * FROM new_student_classes WHERE id = ?', [id]);
    // console.log('根据ID获取新生分班信息result:', result.rows[0]);


    if (result.rows.length === 0) {
      return res.status(404).json({
        message: '新生分班信息不存在'
      });
    }
    // 将数据存入缓存，过期时间设为1小时
    await cache.set(cacheKey, result.rows[0], 3600);

    res.json({
      newStudentClass: result.rows[0],
      source: 'database'
    });
  } catch (error) {
    logger.error('根据ID获取新生分班信息错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 模糊查询新生分班信息
 */
const searchNewStudentClasses = async (req, res) => {
  console.log('模糊查询新生分班信息');

  try {
    const { keyword } = req.query;
    if (!keyword) {
      return res.status(400).json({
        message: '请提供搜索关键词'
      });
    }

    const cacheKey = `search:newStudentClasses:${keyword}`;

    // 尝试从缓存获取数据
    const cachedData = await cache.get(cacheKey);
    if (cachedData) {
      return res.json({
        newStudentClasses: cachedData,
        source: 'cache'
      });
    }

    // 缓存未命中，从数据库获取
    const result = await query(
      'SELECT * FROM new_student_classes WHERE student_name LIKE ?',
      [`%${keyword}%`]
    );

    // 将数据存入缓存，过期时间设为1小时
    await cache.set(cacheKey, result.rows, 3600);

    res.json({
      newStudentClasses: result.rows,
      source: 'database'
    });
  } catch (error) {
    logger.error('模糊查询新生分班信息错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};


/**
 * 创建新的新生分班信息
 */
const createNewStudentClass = async (req, res) => {
  try {
    const { student_name, gender, class_name, head_teacher, head_teacher_phone, class_location, remarks } = req.body;

    // 创建新记录
    await query(
      'INSERT INTO new_student_classes (student_name, gender, class_name, head_teacher, head_teacher_phone, class_location, remarks) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [student_name, gender, class_name, head_teacher, head_teacher_phone, class_location, remarks]
    );

    // 获取创建的记录
    const selectResult = await query(
      'SELECT * FROM new_student_classes WHERE student_name = ? AND class_name = ?',
      [student_name, class_name]
    );

    logger.info(`新生分班信息创建: ${selectResult.rows[0].student_name} (班级: ${selectResult.rows[0].class_name})`);

    // 清除缓存，确保下次获取时从数据库读取最新数据
    await cache.del('newStudentClasses');

    res.status(201).json({
      message: '新生分班信息创建成功',
      newStudentClass: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('创建新生分班信息错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 更新新生分班信息
 */
const updateNewStudentClass = async (req, res) => {
  try {
    const { id } = req.params;
    const { student_name, gender, class_name, head_teacher, head_teacher_phone, class_location, remarks } = req.body;

    // 检查记录是否存在
    const existingRecord = await query('SELECT * FROM new_student_classes WHERE id = ?', [id]);

    if (existingRecord.rows.length === 0) {
      return res.status(404).json({
        message: '新生分班信息不存在'
      });
    }

    // 准备更新字段
    const updateFields = [];
    const params = [];

    if (student_name) {
      updateFields.push('student_name = ?');
      params.push(student_name);
    }

    if (gender) {
      updateFields.push('gender = ?');
      params.push(gender);
    }

    if (class_name) {
      updateFields.push('class_name = ?');
      params.push(class_name);
    }

    if (head_teacher) {
      updateFields.push('head_teacher = ?');
      params.push(head_teacher);
    }

    if (head_teacher_phone) {
      updateFields.push('head_teacher_phone = ?');
      params.push(head_teacher_phone);
    }

    if (class_location) {
      updateFields.push('class_location = ?');
      params.push(class_location);
    }

    if (remarks) {
      updateFields.push('remarks = ?');
      params.push(remarks);
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    params.push(id);

    // 更新记录
    await query(
      `UPDATE new_student_classes SET ${updateFields.join(', ')} WHERE id = ?`,
      params
    );

    // 获取更新后的记录
    const selectResult = await query(
      'SELECT * FROM new_student_classes WHERE id = ?',
      [id]
    );

    logger.info(`新生分班信息更新: ${selectResult.rows[0].student_name} (班级: ${selectResult.rows[0].class_name})`);

    // 清除相关缓存
    await cache.del('newStudentClasses');
    await cache.del(`newStudentClass:${id}`);

    res.json({
      message: '新生分班信息更新成功',
      newStudentClass: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('更新新生分班信息错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 删除新生分班信息
 */
const deleteNewStudentClass = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查记录是否存在
    const existingRecord = await query('SELECT * FROM new_student_classes WHERE id = ?', [id]);

    if (existingRecord.rows.length === 0) {
      return res.status(404).json({
        message: '新生分班信息不存在'
      });
    }

    // 删除记录
    await query('DELETE FROM new_student_classes WHERE id = ?', [id]);

    logger.info(`新生分班信息删除: ${existingRecord.rows[0].student_name} (班级: ${existingRecord.rows[0].class_name})`);

    // 清除相关缓存
    await cache.del('newStudentClasses');
    await cache.del(`newStudentClass:${id}`);

    res.json({
      message: '新生分班信息删除成功'
    });
  } catch (error) {
    logger.error('删除新生分班信息错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

export {
  getNewStudentClasses,
  getNewStudentClassById,
  createNewStudentClass,
  updateNewStudentClass,
  deleteNewStudentClass,
  searchNewStudentClasses
};